package com.leeh.jsontest;

import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

public class Network {
    public static final String CONTENT_TYPE = "Content-Type";
    public static final String APPLICATION_JSON = "application/json";
    public static final String HTML_TEXT = "text/html";
    public static final String METHOD_GET = "GET";
    public static final String METHOD_POST = "POST";
    public static final String METHOD_PUT = "PUT";
    public static final String METHOD_PATCH = "PATCH";
    public static final String METHOD_DELETE = "DELETE";
    public static final String EDIT_CODE_GBK = "gbk";
    public static final String EDIT_CODE_UTF_8 = "utf-8";
    public static final String URL_INIT = "http://192.168.10.194:3000";

    private HttpURLConnection httpConn = null;

    public Network(URL connUrl, String method) {
        initNetWork(connUrl, method);
    }

    public Network(URL connUrl, String method, String referer, String cookie) {
        initNetWork(connUrl, method);
        httpConn.addRequestProperty("Referer", referer);
        httpConn.addRequestProperty("Cookie", cookie);
    }

    /**
     * 初始化网络
     *
     * @param connUrl
     * @param method
     * @throws IOException
     */
    private void initNetWork(URL connUrl, String method) {
        try {
            httpConn = (HttpURLConnection) connUrl.openConnection();
            if (method.equals(Network.METHOD_POST)) {
                httpConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConn.addRequestProperty("Upgrade-Insecure-Requests", "1");
                httpConn.addRequestProperty("Connection", "keep-alive");
                httpConn.addRequestProperty("Cache-Control", "max-age=0");
                httpConn.addRequestProperty("User-Agent",
                        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3)");
                httpConn.setDoOutput(true); //这个设置之后 默认为post请求
            }
            Log.i(TAG, "initNetWork: " + method);
            httpConn.setRequestMethod(method);
            httpConn.setUseCaches(false);
            httpConn.setDoInput(true);
            httpConn.setConnectTimeout(20000);
            httpConn.setReadTimeout(30000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取无参数据
     *
     * @param editCode
     * @return
     * @throws IOException
     */
    public String getData(String editCode) {

        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), editCode));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            httpConn.disconnect();
        }


        return sb.toString();
    }

    /**
     * 获取cookie
     *
     * @return
     * @throws IOException
     */
    public String getCookie() {
        List<String> cookieList = null;
        try {
            httpConn.connect();
            cookieList = httpConn.getHeaderFields().get("Set-Cookie");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpConn.disconnect();
        }
        if (cookieList != null) {
            return cookieList.get(0);
        } else {
            return null;
        }
    }

    /**
     * 获取数据byte[]
     *
     * @return
     * @throws IOException
     */
    public byte[] getBytes() {
        InputStream ins = null;
        ByteArrayOutputStream outs = null;
        byte[] buffer = null;
        try {
            ins = httpConn.getInputStream();
            outs = new ByteArrayOutputStream();
            buffer = new byte[1024];
            int len = 0;
            while ((len = ins.read(buffer)) != -1) {
                outs.write(buffer, 0, len);
            }
            buffer = outs.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outs != null) {
                    outs.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            httpConn.disconnect();
        }
        return buffer;
    }

    /**
     * 有参数  获取数据
     *
     * @param params
     * @param editCode
     * @return
     * @throws IOException
     */
    public String getData(Map<String, String> params, String editCode) {
        DataOutputStream out = null;
        String strData = null;
        try {
            StringBuilder param = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                param.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            out = new DataOutputStream(httpConn.getOutputStream());
            out.writeBytes(param.toString().substring(1));
            out.flush();
            strData = getData(editCode);
            Log.i(TAG, "getData: " + strData);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strData;
    }

    public boolean connectNetwork() {
        int code = 0;
        try {
            httpConn.connect();
            code = httpConn.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return (code == HttpURLConnection.HTTP_OK);
        }
    }

}
